package com.fuhao.workerQueue;

import com.fuhao.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zhang
 * @title: consumer1
 * @projectName simplerabbit
 * @description: TODO
 * @date 2019/5/1821:43
 */
public class consumer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitUtils.getConnection();

        final Channel channel = connection.createChannel();
        //公平分发的话需要保证每次只接收一条消息
        channel.basicQos(1);//保证一次只分发一个
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body,"UTF-8");
                System.out.println("消费者2接收消息 "+ msg );
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }

            }
        };
        //若公平分发，把ack应答改成flase，为手动应答
        channel.basicConsume("worker_queue",false,consumer);
    }
}
